package ext.generic.doc;

import java.beans.PropertyVetoException;

import java.io.*;

import java.util.*;

import com.ptc.core.meta.common.IdentifierFactory;

import ext.com.core.CoreUtil;

import wt.content.ApplicationData;
import wt.content.ContentHelper;
import wt.content.ContentHolder;
import wt.content.ContentItem;
import wt.content.ContentRoleType;
import wt.content.ContentServerHelper;
import wt.content.FormatContentHolder;

import wt.doc.DepartmentList;
import wt.doc.DocumentType;
import wt.doc.WTDocument;
import wt.doc.WTDocumentMaster;

import wt.enterprise.EnterpriseHelper;

import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;

import wt.folder.Folder;
import wt.folder.FolderHelper;

import wt.iba.value.service.LoadValue;

import wt.inf.container.WTContainer;
import wt.inf.container.WTContainerHelper;
import wt.inf.container.WTContainerRef;

import wt.method.RemoteAccess;

import wt.pom.Transaction;

import wt.query.OrderBy;
import wt.query.QuerySpec;

import wt.services.applicationcontext.implementation.DefaultServiceProvider;

import wt.session.SessionServerHelper;

import wt.type.Typed;
import wt.type.TypedUtility;

import wt.util.WTException;
import wt.util.WTProperties;

import wt.vc.VersionControlHelper;

import org.apache.poi.xwpf.usermodel.*;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText;

import wt.vc.Iterated;
import wt.vc.config.ConfigHelper;
import wt.vc.config.ConfigSpec;
import wt.vc.config.LatestConfigSpec;


public class DocUtil2 implements RemoteAccess, Serializable
{
    public static boolean VERBOSE = false;
    public static WTProperties wtProperties;
    public static String CLASSNAME = "";
    public static final IdentifierFactory IDENTIFIER_FACTORY = (IdentifierFactory) DefaultServiceProvider.getService(com.ptc.core.meta.common.IdentifierFactory.class, "logical");

    static
    {
        CLASSNAME = DocUtil2.class.getName();
        try
        {
            wtProperties = WTProperties.getLocalProperties();
            VERBOSE = wtProperties.getProperty("ext.generic.doc.verbose", false);
        }
        catch (java.io.IOException ioe)
        {
            ioe.printStackTrace();
        }
    }

    /**
     * 以当前用户身份创建空壳文档
     *
     * @param container
     * @param folder
     * @param docName
     * @param title
     * @param description
     * @param softTypeLogicId
     * @param ibaAttributes
     * @return
     * @throws WTException
     */
    public static WTDocument createDocumentWithoutContent(WTContainer container, Folder folder, String docName, String title, String description, String softTypeLogicId,
                                                          Hashtable ibaAttributes) throws WTException
    {
        if (VERBOSE)
        {
            System.out.println(">>>" + CLASSNAME + ".createDocumentWithoutContent()");
        }
        boolean flag = SessionServerHelper.manager.setAccessEnforced(false);
        WTDocument doc = WTDocument.newWTDocument();
        try
        {
            // doc.setNumber(docNumber);
            doc.setName(docName);
            doc.setDocType(DocumentType.toDocumentType("$$Document"));
            doc.setDepartment(DepartmentList.toDepartmentList("DOCUMENTATION"));
            LoadValue.setType(doc, softTypeLogicId);
            doc.setContainer(container);
            doc.setTitle(title);
            doc.setDescription(description);
            FolderHelper.assignLocation(doc, folder);
            doc = (WTDocument) PersistenceHelper.manager.save(doc);
            if (ibaAttributes != null && ibaAttributes.size() > 0)
                doc = (WTDocument) ext.com.iba.IBAUtil.setSoftTypeIBAValues((Typed) doc, ibaAttributes);
        }
        catch (Exception exp)
        {
            throw new WTException(exp);
        }
        finally
        {
            SessionServerHelper.manager.setAccessEnforced(flag);
        }
        if (VERBOSE)
            System.out.println("<<<" + CLASSNAME + ".createDocumentWithoutContent()");
        return doc;
    }

    /**
     * 获取文档模版
     * @param templateName
     * @param container
     * @return
     * @throws WTException
     */
    public static WTDocument getDocTemplate(String templateName, WTContainer container) throws WTException
    {
        if (VERBOSE)
        {
            System.out.println(">>>" + CLASSNAME + ".getDocTemplate()");
        }
        WTDocument templateDoc = null;
        QuerySpec queryspec = new QuerySpec(WTDocument.class);
        OrderBy[] orderby = null;
        boolean includeEnabledOnly = true;
        boolean lookup = true;
        boolean removeOverridden = true;
        QueryResult queryresult = EnterpriseHelper.service.getTemplates(container, queryspec, orderby, includeEnabledOnly, lookup, removeOverridden);
        while (queryresult.hasMoreElements())
        {
            WTDocument doc = (WTDocument) queryresult.nextElement();
            if (doc.getName().equals(templateName))
            {
                templateDoc = doc;
                System.out.println("templateDoc=" + templateDoc);
                break;
            }
        }
        if (templateDoc != null)
        {
            templateDoc = getLatestWTDocument((WTDocumentMaster) templateDoc.getMaster());
        }
        else
        {
            System.out.println("系统中没有找到名为:" + templateName + "的模板!");
        }
        if (VERBOSE)
            System.out.println("<<<" + CLASSNAME + ".getDocTemplate()");
        return templateDoc;
    }

    /**
     * 设置单元格值,POI3.6填写会增加一个段落，本函数已修正
     * @param cell
     * @param value
     */
    public static void setCellTextValue(XWPFTableCell cell, String value)
    {
        cell.setText(value);
        CTP[] ctpArr = cell.getCTTc().getPArray();
        CTP[] newctpArr =
        { ctpArr[0] };
        cell.getCTTc().setPArray(newctpArr);
    }

    /**
     * 更新FormatContentHolder的主文件
     * @param holder
     * @param mainFile
     * @param fileName
     * @param isDeleteOldPrimary
     * @return
     * @throws Exception
     */
    public static FormatContentHolder updateMainContentsFromFilePath(FormatContentHolder holder, File mainFile, boolean isDeleteOldPrimary) throws Exception
    {
        if (VERBOSE)
        {
            System.out.println(">>>>>>>>>>>>>>>" + CLASSNAME + ".updateMainContentsFromFilePath");
        }
        if (isDeleteOldPrimary)
        {
            // 删除主文件
            holder = (FormatContentHolder) ContentHelper.service.getContents(holder);
            ContentItem item = ContentHelper.getPrimary(holder);
            ContentServerHelper.service.deleteContent(holder, item);
        }

        holder = (FormatContentHolder) PersistenceHelper.manager.refresh(holder);
        holder = (FormatContentHolder) ContentHelper.service.getContents(holder);

        ApplicationData data = ApplicationData.newApplicationData(holder);
        data.setRole(ContentRoleType.PRIMARY);

        data.setFileName(mainFile.getName()); // 总是忽略文件重名错误
        data = ContentServerHelper.service.updateContent(holder, data, mainFile.getAbsolutePath());
        if (VERBOSE)
        {
            System.out.println("<<<<<<<<<<<<<<<<<<<" + CLASSNAME + ".updateMainContentsFromFilePath");
        }
        return holder;
    }

    /**
     * 下载主文件
     * @param contentHolder
     * @param pathAndName
     * @return
     * @throws WTException
     */
    public static boolean downloadPrimaryFile(ContentHolder contentHolder, String pathAndName) throws WTException
    {
        FormatContentHolder aFormatContentHolder = null;
        boolean rtnValue = true;
        if (VERBOSE)
        {
            System.out.println(">>>>>>>>>>>>>>>>>>>>>>" + CLASSNAME + ".downloadPrimaryFile");
        }
        if (contentHolder == null)
        {
            return false;
        }

        try
        {
            aFormatContentHolder = (FormatContentHolder) ContentHelper.service.getContents(contentHolder);
        }
        catch (PropertyVetoException e1)
        {
            e1.printStackTrace();
        }
        ApplicationData primary = (ApplicationData) ContentHelper.getPrimary(aFormatContentHolder);

        if (primary != null)
        {
            try
            {
                ContentServerHelper.service.writeContentStream(primary, pathAndName);
            }
            catch (IOException e)
            {
                System.out.println("写文件错误" + pathAndName);
                rtnValue = false;
            }
        }
        if (VERBOSE)
        {
            System.out.println("<<<<<<<<<<<<<<<<<<<<<" + CLASSNAME + ".downloadPrimaryFile");
        }
        return rtnValue;
    }

    /**
     * 该方法 根据 文档的master 获取该文档的最新小版本文档.
     *
     * @param     doc_master 要搜索关联的文档 master
     * @return    WTDocument 最新小版本文档
     * @throws WTException
     *
     * <br><br>
     * <b>Revision History</b>
     * <br><b>Rev:</b> 1.0 - 2006/03/06, Tracy Dou
     * <br><b>Comment:</b> Initial release.
     */
    public static WTDocument getLatestWTDocument(WTDocumentMaster doc_master) throws WTException
    {
        Iterated iter = null;
        boolean flag = false;
        LatestConfigSpec latestconfigspec = new LatestConfigSpec();
        QueryResult queryresult = ConfigHelper.service.filteredIterationsOf(doc_master, latestconfigspec);
        if (queryresult.size() <= 0)
        {
            ConfigSpec configspec = ConfigHelper.service.getDefaultConfigSpecFor(WTDocumentMaster.class);
            queryresult = ConfigHelper.service.filteredIterationsOf(doc_master, configspec);
        }

        while (queryresult.hasMoreElements() && (!flag))
        {
            iter = (Iterated) (queryresult.nextElement());
            flag = iter.isLatestIteration();
        }
        return (WTDocument) iter;
    }


    /**
     *
     * @param args
     * @throws WTException
     */
    public static void main(String[] args) throws WTException
    {
    }
}
